package mj.scott.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import mj.scott.common.Result;
import mj.scott.common.utils.JwtUtils;
import mj.scott.common.utils.PasswordUtils;
import mj.scott.mapper.EmployeeMapper;
import mj.scott.pojo.dto.EmployeeLoginDTO;
import mj.scott.pojo.entity.Employee;
import mj.scott.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

/**
 * 员工信息 服务实现类
 * @author Scott
 * @since 2025-08-15
 */
@Slf4j
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private JwtUtils jwtUtils;
    @Override
    public Result login(EmployeeLoginDTO employeeLoginDTO) {

        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        // 1. 根据用户名查询用户
        Employee employee = employeeMapper.selectByUsername(username);
        if (employee == null) {
            return Result.error("用户名不存在");
        }

        // 2. 验证密码（使用BCrypt比对明文与加密密码）
        boolean passwordValid = PasswordUtils.matches(password, employee.getPassword());
        log.info(password + " " +employee.getPassword());
        if (!passwordValid) {
            return Result.error("密码错误");
        }

        // 3. 生成JWT令牌（原有逻辑不变）
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", employee.getUsername());
        String token = jwtUtils.generateToken(claims);

        // 4. 返回结果
        return Result.success("登录成功", token);
    }
}
